package com.hfb.mashibing.alip8.juc.c020_01_interview.A1B2C3;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 *  互联网一线大厂面试题：
 *      徒手写出：2个不同的线程，交替输出A1B2C3。。。
 *
 * 线程排序问题
 * 思路：利用 2个容量各为1的阻塞队列 和 Unsafe，
 *      分别依次遍历字母队列和数字队列
 */
/**
 * 很多队列都能实现,这里使用数组阻塞队列举例
 */
public class A1B2C3BlockingQueue {

    private static char[] charsLetter = "ABCDEFGHI".toCharArray();
    private static char[] charsNumber = "123456789".toCharArray();

    static BlockingQueue qLetter = new ArrayBlockingQueue(1);
    static BlockingQueue qNumber = new ArrayBlockingQueue(1);

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {

        new Thread(()->{
            for (int i = 0; i < charsLetter.length; i++) {
                try {
                    System.out.print(qLetter.take());
                    qNumber.put(charsNumber[i]);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println();
        }).start();
        new Thread(()->{
            for (int i = 0; i < charsNumber.length; i++) {
                try {
                    qLetter.put(charsLetter[i]);
                    System.out.print(qNumber.take());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();


    }

}
